<template>
  <div>
    <el-form
      ref="projectFormRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="typeId">
            <el-select
              v-model="form.typeId"
              clearable
              @change="changeType"
              :disabled="flag"
              placeholder="请选择产品名称"
              style="width: 100%"
            >
              <el-option
                v-for="dict in deviceModelList"
                :key="dict.id"
                :label="dict.deviceModel"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单价（元）">
            <el-input
              v-model="form.unitPrice"
              placeholder="请输入单价（元）"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="number">
            <el-input
              :disabled="flag"
              v-model.number="form.number"
              placeholder="请输入数量"
              @change="changNumber"
              disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总价（元）" prop="totalPrice">
            <el-input
              v-model="form.totalPrice"
              placeholder="请输入总价（元）"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="设备编号" prop="imei" v-if="networkType == '2'">
            <el-input
              :disabled="flag"
              v-model="form.imei"
              placeholder="请输入设备编号"
              style="width: 43.5%"
            />
          </el-form-item>
          <el-form-item label="设备编号" v-else>
            <el-input
              :disabled="flag"
              v-model="form.imei"
              placeholder="请输入设备编号"
              style="width: 43.5%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工单位" prop="constructionUnitId">
            <el-select
              :disabled="flag"
              v-model="form.constructionUnitId"
              @change="changeVal"
              clearable
              placeholder="请选择施工单位"
              style="width: 100%"
            >
              <el-option
                v-for="dict in constructionUnitList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工人员" prop="constructionPersonnel">
            <el-input
              :disabled="flag"
              v-model="form.constructionPersonnel"
              placeholder="请输入施工人员"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工时间" prop="constructionDate">
            <el-date-picker
              :disabled="flag"
              v-model="form.constructionDate"
              style="width: 100%"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              :disabled="flag"
              v-model="form.notes"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 8 }"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <div style="text-align: right">
            <el-button
              v-if="!flag"
              type="primary"
              style="margin-left: 20px"
              @click="submitFormDebounceHandler"
              >确 定</el-button
            >
            <el-button @click="goCancel">取 消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script setup name="prodect_form">
import {
  constructionUnit,
  deviceModel,
  elderlyOrientedRemodelProductSave,
  elderlyOrientedRemodelProductUpdata,
  getProductSelectOptionsAPI,
} from "@/api/AgeAppropriate";

import { debounce } from "@/utils/debounce.js";

const { homeBedApplyId, formatDate, flag } = defineProps({
  homeBedApplyId: {
    type: String || Number,
    required: true,
  },
  formatDate: {
    type: Object,
    required: true,
  },
  flag: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const { proxy } = getCurrentInstance()
const constructionUnitList = ref([])
const deviceModelList = ref([])
const networkType = ref('');
const emits = defineEmits("closed");
const disabledDate = (time) => {
  // 禁用过去的日期，只允许选择今天以及今天之后的日期
  return time.getTime() < Date.now() - 8.64e7;
};

const data = reactive({
  form: {
    number: 1,
  },
  rules: {
    typeId: [{ required: true, message: "请选择产品名称", trigger: "change" }],
    number: [{ required: true, message: "请输入数量", trigger: "blur" }],
    constructionUnitId: [
      { required: true, message: "请选择施工单位", trigger: "change" },
    ],
    constructionPersonnel: [
      { required: true, message: "请输入施工人员", trigger: "blur" },
    ],
    constructionDate: [
      { required: true, message: "请选择施工时间", trigger: "change" },
    ],
    imei: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
    totalPrice: [{ required: true, message: "请输入总价", trigger: "blur" }],
  },
});

const { form, rules } = toRefs(data)

onMounted(() => {
  if (formatDate) {
    form.value = formatDate;
  }
  form.value.homeBedApplyId = homeBedApplyId;
})

/** 提交按钮 */
const submitFormDebounceHandler = debounce(submitForm, 500);

/**
 * 初始化下拉框等数据
 */
const init = () => {
  getConstructionUnit();
  // TODO: Removed code
  // getDeviceModel();
  getProductSelectOptions()
};

const getProductSelectOptions = () => {
  const obj = {
    page: 1,
    limit: 999,
  };
  getProductSelectOptionsAPI(obj).then((res) => {
    deviceModelList.value = res.productSelectOptionsList;
  })
}

function submitForm() {
  proxy.$refs["projectFormRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        elderlyOrientedRemodelProductUpdata(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          emits("closed", true);
        })
      } else {
        elderlyOrientedRemodelProductSave(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          emits("closed", true);
        })
      }
    }
  });
}

function changeVal(val) {
  form.value.constructionUnit = constructionUnitList.value.find(
    (item) => item.id == val,
  )?.name;
}

// function getDeviceModel() {
//   const obj = {
//     page: 1,
//     limit: 999,
//   }
//   deviceModel(obj).then((res) => {
//     console.log("【res】 = ", res);
//     deviceModelList.value = res.modelList;
//   })
// }

function changeType(val) {
  networkType.value = deviceModelList.value.find(
    (item) => item.id == val,
  )?.networkType;
  form.value.unitPrice = deviceModelList.value.find(
    (item) => item.id == val,
  )?.unitPrice;
  form.value.name = deviceModelList.value.find(
    (item) => item.id == val,
  )?.deviceModel;
  form.value.deviceTypeId = deviceModelList.value.find(
    (item) => item.id == val,
  )?.deviceTypeId
  if (form.value.number) {
    form.value.totalPrice = form.value.unitPrice * form.value.number;
  } else {
    form.value.totalPrice = 0;
  }
}

function changNumber(val) {
  if (!(typeof (val - 0) == "number" && !isNaN(val - 0))) {
    proxy.$modal.msgError("请正确输入数量");
    form.value.number = "";
  }
  form.value.totalPrice = form.value.unitPrice * form.value.number;
}

function getConstructionUnit() {
  const obj = {
    page: 1,
    limit: 999,
  };
  constructionUnit(obj).then((res) => {
    constructionUnitList.value = res.page.list;
  })
}
function goCancel() {
  emits("closed");
}

init();
</script>
